<?php

namespace App\Traits;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;

trait ApiResponse
{
    /**
     * 成功响应
     */
    protected function success($data = [], string $message = '操作成功', int $code = 200): JsonResponse
    {
        // 对于成功响应，code就是HTTP状态码
        $httpStatus = $code;
        
        return response()->json([
            'code' => $code,
            'message' => $message,
            'data' => $data,
            'meta' => [
                'timestamp' => time() * 1000,
                'request_id' => Str::uuid()->toString(),
            ]
        ], $httpStatus);
    }

    /**
     * 错误响应
     */
    protected function error(string $message = '操作失败', int $code = 400, $errors = []): JsonResponse
    {
        // 将业务错误码映射到HTTP状态码
        $httpStatus = $this->mapBusinessCodeToHttpStatus($code);
        
        return response()->json([
            'code' => $code,
            'message' => $message,
            'errors' => $errors,
            'meta' => [
                'timestamp' => time() * 1000,
                'request_id' => Str::uuid()->toString(),
            ]
        ], $httpStatus);
    }

    /**
     * 处理异常并返回错误响应
     */
    protected function handleException(\Exception $e, int $defaultCode = 500): JsonResponse
    {
        $code = $e->getCode();
        // 确保错误码是整数类型
        if (!is_int($code) || $code === 0) {
            $code = $defaultCode;
        }
        return $this->error($e->getMessage(), $code);
    }

    /**
     * 将业务错误码映射到HTTP状态码
     */
    private function mapBusinessCodeToHttpStatus(int $businessCode): int
    {
        // 特殊状态码直接返回
        if ($businessCode === 401) {
            return 401;
        }
        
        if ($businessCode === 422) {
            return 422;
        }
        
        // 房间相关错误 (10xxx)
        if ($businessCode >= 10001 && $businessCode <= 10099) {
            switch ($businessCode) {
                case 10001: // 房间不存在
                    return 404;
                case 10002: // 房间已关闭
                case 10003: // 房间已过期
                case 10005: // 您已在此房间中
                case 10006: // 房间人数已达上限
                    return 400;
                case 10004: // 无权限访问房间
                    return 403;
                default:
                    return 400;
            }
        }
        
        // 订单相关错误 (20xxx)
        if ($businessCode >= 20001 && $businessCode <= 20099) {
            switch ($businessCode) {
                case 20001: // 您已在此房间中提交过订单
                    return 409; // Conflict - 资源冲突
                case 20002: // 订单不存在
                case 20005: // 菜品不存在
                    return 404;
                case 20003: // 无权限操作订单
                    return 403;
                case 20004: // 订单状态不允许操作
                case 20006: // 菜品不可用
                    return 400;
                default:
                    return 400;
            }
        }
        
        // 认证相关错误 (40xxx)
        if ($businessCode >= 40001 && $businessCode <= 40099) {
            switch ($businessCode) {
                case 40001: // 微信授权失败
                    return 400;
                case 40002: // 用户已被禁用
                    return 403;
                default:
                    return 400;
            }
        }
        
        // 系统错误 (50xxx)
        if ($businessCode >= 50001 && $businessCode <= 50099) {
            return 500;
        }
        
        // 默认返回400
        return 400;
    }

    /**
     * 分页响应
     */
    protected function paginated($data, string $message = '获取成功', int $code = 200): JsonResponse
    {
        return response()->json([
            'code' => $code,
            'message' => $message,
            'data' => [
                'items' => $data->items(),
                'pagination' => [
                    'current_page' => $data->currentPage(),
                    'per_page' => $data->perPage(),
                    'total' => $data->total(),
                    'last_page' => $data->lastPage(),
                    'has_more' => $data->hasMorePages(),
                ]
            ],
            'meta' => [
                'timestamp' => time() * 1000,
                'request_id' => Str::uuid()->toString(),
            ]
        ], $code);
    }

    /**
     * 创建成功响应
     */
    protected function created($data = [], string $message = '创建成功'): JsonResponse
    {
        return $this->success($data, $message, 201);
    }

    /**
     * 无内容响应
     */
    protected function noContent(string $message = '操作成功'): JsonResponse
    {
        return $this->success([], $message, 204);
    }
}
